package org.ljdp.bootstrap;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

/**
 * 命令行参数解析
 * @author Administrator
 *
 */
public class CliParser {

	public AppInfoBean parser(String[] args) {
		HelpFormatter formatter = new HelpFormatter();
		// create Options object
		Options options = new Options();
		options.addOption("name", true, "应用名称");
		options.addOption("boot", true, "业务模块启动时执行的线程（需要实现Runnable），如果没有设置，则使用LJDP架构启动");
		options.addOption("shutdown", true, "业务模块关闭时执行的线程（需要继承Thread），不是必须");
		options.addOption("web", true, "使用web模式启动，填写web应用目录，不设置则默认用jar方式启动");
		options.addOption("h", false, "帮助");
		
		// create the parser
	    CommandLineParser parser = new DefaultParser();
	    // parse the command line arguments
        try {
			CommandLine line = parser.parse( options, args );
			String appname = line.getOptionValue("name");
			if(line.hasOption("h")) {
	        	formatter.printHelp("LJDP", options );
	        }
			String deployType = AppInfoBean.DEPLOY_JAR;
			String deployPath = null;
			if(line.hasOption("web")) {
				String webdir = line.getOptionValue("web");
				if(webdir != null && webdir.length() > 0) {
					deployType = AppInfoBean.DEPLOY_WEB;
					deployPath = webdir;
				}
			}
			AppInfoBean b= new AppInfoBean(appname, deployType, deployPath);
			
			if(line.hasOption("boot")) {
				b.setBootThread(line.getOptionValue("boot"));
			}
			if(line.hasOption("shutdown")) {
				b.setShutdownThread(line.getOptionValue("shutdown"));
			}
			
			return b;
		} catch (ParseException e) {
			e.printStackTrace();
		}
        return null;
	}
}
